<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="BOM编码" prop="bomId">
        <el-input
          v-model="queryParams.bomId"
          placeholder="请输入BOM编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="BOM名称" prop="bomName">
        <el-input
          v-model="queryParams.bomName"
          placeholder="请输入BOM名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:bom:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:bom:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:bom:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:bom:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="BOMid" align="center" prop="id" />
      <el-table-column label="BOM编码" align="center" prop="bomId" />
      <el-table-column label="BOM名称" align="center" prop="bomName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="HandleExamine(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:bom:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:bom:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改BOM对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="BOM编码" prop="bomId">
          <el-input v-model="form.bomId" placeholder="请输入BOM编码" :readonly="!isVisible"/>
        </el-form-item>
        <el-form-item label="BOM名称" prop="bomName">
          <el-input v-model="form.bomName" placeholder="请输入BOM名称" :readonly="!isVisible"/>
        </el-form-item>

        <el-divider>原 料 列 表</el-divider>
        <el-button v-if="isVisible" style="margin-bottom: 10px;" type="primary" @click="processadd">添 加</el-button>
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.mtrs">
            <el-table-column label="原料" align="" prop="mtrName" align="center">
              <template slot-scope="scope" >
                <el-select v-model="scope.row.matId" filterable placeholder="请选择"
                           @change="(option) => mtrchang(option, scope.$index)" :disabled="!isVisible">

                  <el-option v-for="item in matselectoption" :key="item.matId" :label="item.matId" :value="item.matId">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="数量" align="center"  width="230px">
              <template slot-scope="scope">
                <el-input-number id="inputNumber" v-model:value="scope.row.num" :min="0" :precision="0" :disabled="!isVisible"/>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isVisible">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="processadd(scope.$index, scope.row)"
                           v-hasPermi="['mes:proinfo:edit']">增加</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="processdel(scope.$index)"
                           v-hasPermi="['mes:proinfo:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isVisible">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBom, getBom, delBom, addBom, updateBom } from "@/api/system/bom";
import {listMaterial} from "@/api/system/material";
import {addMatbom, fetchMatIdsByBomId, updateMatbom} from "@/api/system/matbom";
import {fetchProcessIdsByTechId} from "@/api/system/pro";
import {getTec} from "@/api/system/tec";

export default {
  name: "Bom",
  data() {
    return {
      /***    **/
      isVisible : false,

      //原料下拉框数据
      matselectoption:[],
      // 用来记录已选择的原料id
      usedIds: [],
      //bom拥有的原料
      matbom:[],

      /***   **/
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BOM表格数据
      bomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bomId: null,
        bomName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bomId: [
          { required: true, message: "BOM编码不能为空", trigger: "blur" }
        ],
        bomName: [
          { required: true, message: "BOM名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**   **/
    /**
     * 下拉框改变
     * @param {选项值} option
     */
    mtrchang(option, index) {
        //②更新this.form.mtrs的数据
        let ss = this.matselectoption.find(item => item.matId == option)
        if(ss) {
          this.form.mtrs[index].id = ss.id//原料Id
          this.form.mtrs[index].matId = ss.matId//原料Id
          this.form.mtrs[index].bomId = this.form.bomId// 当前 bomId
          this.form.mtrs[index].num = this.form.num //原料数量

        }
        //②
      },

    // mtrchang(option, index) {
    //   // ①检查当前选择的option是否已在usedIds中
    //   if (this.usedIds.includes(option)) {
    //     // 如果已存在，则提示用户并重置选择
    //     this.$message.warning(`第${index + 1}行：该原料已选择过，请选择其他原料。`);
    //     this.$nextTick(() => {
    //       this.form.mtrs[index].id = null; // 重置当前行的id为null或适当默认值
    //     });
    //   } else {
    //     // 如果是新选择，先从usedIds中移除当前行已有的id（如果存在）
    //     if (this.form.mtrs[index].id !== null && !isNaN(this.form.mtrs[index].id)) {
    //       const currentIndex = this.usedIds.indexOf(this.form.mtrs[index].id);
    //       if (currentIndex > -1) {
    //         this.usedIds.splice(currentIndex, 1);
    //       }
    //     }
    //     // 然后添加新选择的id到usedIds
    //     this.usedIds.push(option);
    //     //①
    //
    //     //②更新this.form.mtrs的数据
    //     let ss = this.matselectoption.find(item => item.id == option)
    //     if(ss) {
    //       this.form.mtrs[index].matId = ss.matId//原料Id
    //       this.form.mtrs[index].bomId = this.form.bomId// 当前 bomId
    //       this.form.mtrs[index].num = this.form.num //原料数量
    //     }
    //     //②
    //
    //   }
    //
    // },
    /**
     * 删除原料
     * @param {下标} index
     */
    processdel(index) {
      this.form.mtrs.splice(index, 1)
    },
    /**
     * 添加原料
     * @param {下标} index
     * @param {行数据} row
     */
    processadd(index, row) {
      if (index != undefined) {
        this.form.mtrs.splice(index + 1, 0,
          {
            id:null,
            matId:null,
            bomId:null,
            num: 0
          }
        )
      } else {
        this.form.mtrs.push(
          {
            id:null,
            matId:null,
            bomId:null,
            num: 0
          }
        )
      }
    },

    /** **/
    /** 查询BOM列表 */
    getList() {
      this.loading = true;
      listBom(this.queryParams).then(response => {
        this.bomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      //原料列表
      listMaterial().then((res) => {
        this.matselectoption = res.rows
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bomId: null,
        bomName: null,
        //原料数量
        // mtrQuantity:0,
        oldBomId:null,
        mtrs: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /**
     * 查看按钮操作 */
    HandleExamine(row) {
      this.reset();
      this.isVisible = false;
      const id = row.id || this.ids
      getBom(id).then(response => {
        this.form = response.data;

        this.form.oldBomId = this.form.bomId;

        //根据bomId去查看bom包含的所有原料
        fetchMatIdsByBomId(this.form.bomId).then((res) =>{
          this.matbom = res.data;
          this.form.mtrs = this.matbom

          this.open = true;
          this.title = "查看BOM";
        });
      });
    },





    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isVisible = true;
      this.usedIds = [];
      this.open = true;
      this.title = "添加BOM";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isVisible = true;
      const id = row.id || this.ids
      getBom(id).then(response => {
        this.form = response.data;

        this.form.oldBomId = this.form.bomId;

        //根据bomId去查看bom包含的所有原料
        fetchMatIdsByBomId(this.form.bomId).then((res) =>{
        this.matbom = res.data;
        this.form.mtrs = this.matbom

        this.open = true;
        this.title = "修改BOM";
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      // this.isVisible = false;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.mtrs.findIndex(e => { return e.id == null }) != -1 || this.form.mtrs.length == 0) {
            this.$modal.msgError("请添加或将bom信息填写完整");
          } else {
              // 验证mtrs数组中的每个对象的num是否都已填写
              const hasEmptyNum = this.form.mtrs.some(item => item.num === null || item.num === undefined || isNaN(item.num) || item.num === 0 );

              // 创建一个空对象来存储已经出现过的 matId
              let matIdMap = {};

              // 遍历数组进行检查
              let isMatIdUnique = true;
              for (let i = 0; i < this.form.mtrs.length; i++) {
                let currentMatId = this.form.mtrs[i].matId;
                if (matIdMap[currentMatId]) {
                  // 如果当前的 matId 已经在 map 中出现过，则不唯一
                  isMatIdUnique = false;
                  break;
                } else {
                  // 将当前的 matId 记录到 map 中
                  matIdMap[currentMatId] = true;
                }
              }

              // 现在 isMatIdUnique 变量中存储了 matId 的唯一性检查结果
              console.log("matId 是否唯一：", isMatIdUnique);

              if (hasEmptyNum) {
                this.$message.warning('请检查所有原料的数量，确保已填写！');
              }else {
                if(isMatIdUnique){

                  if (this.form.id != null) {

                    this.form.mtrs.forEach(item => {
                      item.bomId = this.form.bomId;//!!!!!!!!!!!!
                      item.oldBomId = this.form.oldBomId;
                    });

                    updateBom(this.form).then(response => {
                      this.$modal.msgSuccess("修改bom成功");
                      this.open = false;
                      this.getList();
                      return updateMatbom(this.form);
                    })
                    .then(response => {
                      this.$modal.msgSuccess("修改bom原料成功");
                    })
                    .catch(error => {
                      if (error && (error.message === "bom编码重复" || (error.response && error.response.data && error.response.data.message === "bom编码重复"))) {
                        this.$modal.msgError("修改BOM失败，bom编码重复");
                        this.reset();
                      } else {
                        console.error("发生错误:", error);
                        this.$modal.msgError("修改BOM或原料BOM时发生错误");
                      }
                    });


                  } else {
                    // addBom(this.form).then(response => {
                    //   this.$modal.msgSuccess("新增bom成功");
                    //   this.open = false;
                    //   this.getList();
                    // })
                    // .catch(error => {
                    //   // 检查错误信息或状态码来判断是否是“bom编码重复”的错误
                    //   if (error.message === "bom编码重复" || error.response.data.message === "bom编码重复") {
                    //     this.$modal.msgError("新增BOM失败，bom编码重复");
                    //     // 这里不再执行addMatbom，直接返回或做其他处理
                    //     return;
                    //   }
                    // });
                    //
                    // addMatbom(this.form).then(response => {
                    //   this.$modal.msgSuccess("新增原料bom成功");
                    //   this.open = false;
                    //   this.getList();
                    // });

                    addBom(this.form)
                      .then(response => {
                        // 新增bom成功处理
                        this.$modal.msgSuccess("新增bom成功");
                        this.open = false;
                        this.getList();

                        // 继续执行新增原料bom的操作
                        return addMatbom(this.form);
                      })
                      .then(response => {
                        // 新增原料bom成功处理
                        this.$modal.msgSuccess("新增原料bom成功");
                        // 根据业务需要决定是否需要额外的操作，例如刷新列表或关闭窗口等
                      })
                      .catch(error => {
                        // 错误处理逻辑
                        if (error && (error.message === "bom编码重复" || (error.response && error.response.data && error.response.data.message === "bom编码重复"))) {
                          // 特别处理bom编码重复的错误
                          this.$modal.msgError("新增BOM失败，bom编码重复");
                          this.reset();
                        } else {
                          // 处理其他未知错误
                          console.error("发生错误:", error);
                          this.$modal.msgError("新增BOM或原料BOM时发生错误");
                        }
                      });

                  }
                }else {
                  this.$message.warning('原料不能重复！');
                }
              }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除BOM编号为"' + ids + '"的数据项？').then(function() {
        return delBom(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/bom/export', {
        ...this.queryParams
      }, `bom_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
